﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AAA.Database;
using System.IO;

namespace AAA.DataLoader
{
    public class CSVLoader
    {
        private IDatabase _database;
        private string _strSQLStatement;
        private string[] _strDefaultValues = new string[0];
        private bool _hasHeader;
        private string _strErrorMessage;
        private char _cSplitChar = ',';

        public IDatabase Database
        {
            get { return _database; }
            set { _database = value; }
        }

        public string SQLStatement
        {
            get { return _strSQLStatement; }
            set { _strSQLStatement = value; }
        }

        public bool HasHeader
        {
            get { return _hasHeader; }
            set { _hasHeader = value; }
        }

        public string ErrorMessage
        {
            set { _strErrorMessage = value; }
            get { return _strErrorMessage; }
        }

        public string[] DefaultValues
        {
            get { return _strDefaultValues; }
            set { _strDefaultValues = value; }
        }

        public char SplitChar
        {
            get { return _cSplitChar; }
            set { _cSplitChar = value; }
        }

        public void Load(string strFilename)
        {
            _strErrorMessage = null;
            StreamReader sr = null;
            string strLine;
            string[] strHeaders;
            string[] strValues;
            string[] strInsertValues;

            try
            {
                sr = new StreamReader(strFilename, Encoding.Default);

                if (HasHeader && ((strLine = sr.ReadLine()) != null))
                    strHeaders = strLine.Split(_cSplitChar);

                while ((strLine = sr.ReadLine()) != null)
                {
                    strLine = strLine.Replace("'", "''");
                    strValues = strLine.Split(_cSplitChar);

                    strInsertValues = new string[_strDefaultValues.Length + strValues.Length];
                    Array.Copy(_strDefaultValues, strInsertValues, _strDefaultValues.Length);
                    Array.Copy(strValues, 0, strInsertValues, _strDefaultValues.Length, strValues.Length);
                    Database.ExecuteUpdate(SQLStatement, strInsertValues);
                }
            }
            catch (Exception ex)
            {
                _strErrorMessage = ex.Message + "," + ex.StackTrace;
            }
            finally
            {
                if (sr != null)
                    sr.Close();
            }
        }

    }
}
